package com.shupian.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.shupian.domain.ResponseResult;
import com.shupian.domain.dto.UserAddDto;
import com.shupian.domain.dto.UserUpdateDto;
import com.shupian.domain.entity.Role;
import com.shupian.domain.entity.User;
import com.shupian.domain.entity.UserRole;
import com.shupian.domain.vo.PageVo;
import com.shupian.domain.vo.UserByIdVo;
import com.shupian.domain.vo.UserInfoVo;
import com.shupian.domain.vo.UserVo;
import com.shupian.enums.AppHttpCodeEnum;
import com.shupian.exception.SystemException;
import com.shupian.mapper.UserMapper;
import com.shupian.service.RoleService;
import com.shupian.service.UserRoleService;
import com.shupian.service.UserService;
import com.shupian.utils.BeanCopyUtils;
import com.shupian.utils.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 用户表(User)表服务实现类
 *
 * @author makejava
 * @since 2022-07-28 15:02:45
 */
@Service("userService")
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {


    @Autowired
    private UserRoleService userRoleService;

    @Autowired
    private RoleService roleService;
    @Override
    public ResponseResult userInfo() {
        //获取当前用户id
        Long userId = SecurityUtils.getUserId();
        //根据用户id查询用户信息
        User user = getById(userId);
        //分装成UserInfo
        UserInfoVo vo = BeanCopyUtils.copyBean(user,UserInfoVo.class);
        return ResponseResult.okResult(vo);
    }

    @Override
    public ResponseResult updateUserInfo(User user) {
        updateById(user);
        return ResponseResult.okResult();
    }
    @Autowired
    private PasswordEncoder passwordEncoder;
    @Override
    public ResponseResult register(User user) {
        //对数据进行非空判断
        if (!StringUtils.hasText(user.getUserName())){
            throw new SystemException(AppHttpCodeEnum.USERNAME_NOT_NULL);
        }
        if (!StringUtils.hasText(user.getPassword())){
            throw new SystemException(AppHttpCodeEnum.PASSWORD_NOT_NULL);
        }
        if (!StringUtils.hasText(user.getEmail())) {
            throw new SystemException(AppHttpCodeEnum.EMAIL_NOT_NULL);
        }
        if (!StringUtils.hasText(user.getNickName())) {
            throw new SystemException(AppHttpCodeEnum.NICK_NAME_NOT_NULL);
        }

        //对数据进行是否存在的判断
        if(exist(null,user.getUserName(),null,null)){
            throw new SystemException(AppHttpCodeEnum.USERNAME_EXIST);
        }
        if (exist(user.getNickName(),null , null, null)){
            throw new SystemException(AppHttpCodeEnum.NICKNAME_EXIST);
        }
        if (exist(null, null, user.getEmail(), null) ){
            throw new SystemException(AppHttpCodeEnum.EMAIL_EXIST);
        }
        //对密码进行加密
        String encodePassword = passwordEncoder.encode(user.getPassword());
        user.setPassword(encodePassword);
        //存入数据库
        save(user);
        return ResponseResult.okResult();
    }


    @Override
    public ResponseResult getAlluser(Integer pageNum, Integer pageSize, String userName, String phonenumber, String status) {
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.like(StringUtils.hasLength(userName),User::getUserName,userName);
        queryWrapper.eq(StringUtils.hasLength(phonenumber),User::getPhonenumber,phonenumber);
        queryWrapper.eq(StringUtils.hasLength(status),User::getStatus,status);
        Page<User> userPage = new Page<>(pageNum,pageSize);
        page(userPage,queryWrapper);
        List<User> userList = userPage.getRecords();
        List<UserVo> userVos = BeanCopyUtils.copyBeanList(userList, UserVo.class);
        return ResponseResult.okResult(new PageVo(userVos,userPage.getTotal()));
    }

    @Override
    public ResponseResult addUser(UserAddDto userAddDto) {
        //对数据进行是否存在的判断
        if (exist(null, userAddDto.getUserName(), null, null)) {
            throw new SystemException(AppHttpCodeEnum.USERNAME_EXIST);
        }
        if (exist(userAddDto.getNickName(), null, null, null)) {
            throw new SystemException(AppHttpCodeEnum.NICKNAME_EXIST);
        }
        if (exist(null, null, userAddDto.getEmail(), null)) {
            throw new SystemException(AppHttpCodeEnum.EMAIL_EXIST);
        }
        if(exist(null,null,null,userAddDto.getPhonenumber())){
            throw new SystemException(AppHttpCodeEnum.PHONENUMBER_EXIST);
        }
        User user = BeanCopyUtils.copyBean(userAddDto, User.class);
        user.setPassword(passwordEncoder.encode(user.getPassword()));
        save(user);
        List<Long> roleIds = userAddDto.getRoleIds();
        for (Long num: roleIds) {
            userRoleService.save(new UserRole(user.getId(),num));
        }
        return ResponseResult.okResult();
    }

    @Override
    public ResponseResult getUserById(Long id) {
        Map<String,Object> map = new HashMap<>();
        User user = getById(id);
        UserByIdVo userByIdVo = BeanCopyUtils.copyBean(user, UserByIdVo.class);

        List<Long> roleIdsByUserId = userRoleService.getRoleIdsByUserId(id);

        List<Role> list = roleService.list();

        map.put("roleIds",roleIdsByUserId);
        map.put("roles",list);
        map.put("user",userByIdVo);


        return ResponseResult.okResult(map);
    }

    @Override
    public ResponseResult updateUser(UserUpdateDto userUpdateDto) {
        //对数据进行是否存在的判断
        if (exist(null, userUpdateDto.getUserName(), null, null)) {
            throw new SystemException(AppHttpCodeEnum.USERNAME_EXIST);
        }
        if (exist(userUpdateDto.getNickName(), null, null, null)) {
            throw new SystemException(AppHttpCodeEnum.NICKNAME_EXIST);
        }
        if (exist(null, null, userUpdateDto.getEmail(), null)) {
            throw new SystemException(AppHttpCodeEnum.EMAIL_EXIST);
        }
        User user = BeanCopyUtils.copyBean(userUpdateDto, User.class);
        updateById(user);
        List<Long> roleIds = userUpdateDto.getRoleIds();
        for (Long num : roleIds) {
            userRoleService.save(new UserRole(user.getId(), num));
        }
        return ResponseResult.okResult();
    }

    private boolean exist(String nickName,String userName,String email,String phonenumber) {
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(StringUtils.hasText(userName),User::getUserName,userName);
        queryWrapper.eq(StringUtils.hasText(nickName), User::getNickName, nickName);
        queryWrapper.eq(StringUtils.hasText(email), User::getEmail, email);
        queryWrapper.eq(StringUtils.hasText(phonenumber),User::getPhonenumber,phonenumber);
        return count(queryWrapper) > 0;
    }
}

